package cn.elead.chaos.remote.web.remote.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.elead.chaos.remote.web.remote.domain.SysRole;
import cn.elead.chaos.remote.web.remote.mapper.SysRoleMapper;
import cn.elead.chaos.remote.web.remote.service.ISysMenuService;
import cn.elead.chaos.shiro.service.IShiroRealmService;
import cn.elead.chaos.sso.core.user.LoginUser;
import cn.elead.chaos.sso.core.util.SsoUtils;
import cn.hutool.core.util.ObjectUtil;

/**
 * Shiro权限远程服务
 * 
 * @author luopeng
 *
 */
@Service
public class SysShiroRealmService implements IShiroRealmService {

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private ISysMenuService menuService;

	@Override
	public Set<String> selectRoleKeys(String userId) {
		if (SsoUtils.isAdmin(userId)) {
			return Arrays.asList("admin").stream().collect(Collectors.toSet());
		}
		List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId, SsoUtils.getTenant());
		Set<String> permsSet = new HashSet<>();
		for (SysRole perm : perms) {
			if (ObjectUtil.isNotNull(perm)) {
				permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public Set<String> selectPermsByUserId(String userId) {
		if (SsoUtils.isAdmin(userId)) {
			return Arrays.asList("*:*:*").stream().collect(Collectors.toSet());
		}
		return menuService.selectMenuPermsByUserId(userId);
	}

	@Override
	public LoginUser getUser(String token) {
		return SsoUtils.getUser();
	}
}
